package edu.example.student.servlet;

import com.google.gson.Gson;
import edu.example.common.PowerCheck;
import edu.example.manage.servlet.RoomMangeServlet;
import edu.example.manage.utils.JDBCUtils;
import edu.example.order.bean.User;
import edu.example.student.beans.Building;
import edu.example.student.dao.BuildingDao;
import edu.example.student.dao.StudentDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/studentadd")
public class StudentAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*权限*/
        if (!PowerCheck.isAdmin(req)) {
            req.setAttribute("reMessage", "无权访问");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        BuildingDao buildingDao = new BuildingDao();
        List<Building> all = buildingDao.findAll();
        req.setAttribute("builds", all);
        req.getRequestDispatcher("/student/add.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*权限*/
        if (!PowerCheck.isAdmin(req)) {
            req.setAttribute("reMessage", "无权访问");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        //保存学生
        Integer stuid= Integer.valueOf(req.getParameter("stuId"));
        String stuname=req.getParameter("stuname");
        String stusex=req.getParameter("stusex");
        String stupwd=req.getParameter("stupwd");
        String stutel=req.getParameter("stutel");
        String rooms_card=req.getParameter("rooms_card");
        String building_card=req.getParameter("Building_card");
        User user1=new User();
        user1.setId(stuid);
        user1.setName(stuname);
        user1.setGender(stusex);
        user1.setPassword(stupwd);
        user1.setPhone(stutel);
        user1.setBuildingsCard(building_card);
        user1.setRoomsCard(rooms_card);
        Gson gson = new Gson();
        String message = gson.toJson(user1);
        RoomMangeServlet roomMangeServlet = new RoomMangeServlet();
        try {
            roomMangeServlet.submitCheck(resp,
                    "insert into `check`(type, message, obj_type, execution, obj) value(?, ?, ?, ?, ?)",
                    user1.getId(), 0, message, 0, 2, user1.getId());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        resp.sendRedirect("studentlist");
    }
}
